import React, { Component } from 'react';
import { Button, Input } from 'antd-mobile';
import styles from './PlayerDetail.module.less';
import { getPlayerById, savePlayer } from '../../store/playerStore';
import { withRouterParams } from '../../utils/routerHocs';

class PlayerDetail extends Component {
  constructor(props) {
    super(props);
    const { id } = props.params || {};
    const player = id ? getPlayerById(id) : null;

    this.state = {
      id: player ? player.id : '',
      name: player ? player.name : '',
      number: player ? String(player.number) : '',
      isEdit: !!id,
    };
  }

  handleChange = (key, value) => {
    this.setState({ [key]: value });
  };

  handleSave = () => {
    const { id, name, number, isEdit } = this.state;
    const trimmedName = (name || '').trim();
    const trimmedNum = (number || '').trim();
    const numOk = /^\d{1,2}$/.test(trimmedNum);

    if (!trimmedName) {
      alert('球员名称不能为空');
      return;
    }
    if (!numOk) {
      alert('球衣号码必须是0-99的数字');
      return;
    }

    const payload = {
      id: isEdit && id ? id : String(Date.now()),
      name: trimmedName,
      number: Number(trimmedNum),
    };

    savePlayer(payload);
    this.props.navigate('/playerList');
  };

  handleCancel = () => {
    this.props.navigate('/playerList');
  };

  render() {
    const { id, name, number } = this.state;

    return (
      <div className={styles.container}>
        <div className={styles.card}>
          <div className={styles.formItem}>
            <div className={styles.label}>ID（只读）</div>
            <Input value={id} readOnly className={styles.input} placeholder="保存后自动生成" />
          </div>
          <div className={styles.formItem}>
            <div className={styles.label}>球员名称</div>
            <Input value={name} onChange={val => this.handleChange('name', val)} className={styles.input} placeholder="请输入球员名称" />
          </div>
          <div className={styles.formItem}>
            <div className={styles.label}>球衣号码（0-99）</div>
            <Input value={number} onChange={val => this.handleChange('number', val)} className={styles.input} placeholder="请输入球衣号码" />
          </div>
          <div className={styles.btnRow}>
            <Button color="primary" onClick={this.handleSave}>保存</Button>
            <Button onClick={this.handleCancel}>取消</Button>
          </div>
        </div>
      </div>
    );
  }
}

export default withRouterParams(PlayerDetail);


